﻿using Mongodb;
using ProductTool.Dao;
using ProductTool.Entity;
using ProductTool.Tools;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ProductTool.Service
{
    public class ItemService
    {
        ItemDao dao = new ItemDao();
        BrandDao bDao = new BrandDao();
        List<BrandEntity> brandList = new List<BrandEntity>();
        public ItemService() {
            brandList = bDao.QueryBrand();
        }
        public void Process() {
        
            var list = new List<JDItem>();
            int page = 1;
            string maxGoodsSN = dao.QueryMaxGoodsSN();
            if (string.IsNullOrEmpty(maxGoodsSN))
            {
                maxGoodsSN = "";
            }
            List<Task> thList = new List<Task>();
            do
            {
                list = dao.QueryJdItem(page, 10, maxGoodsSN);

                Stopwatch sw = new Stopwatch();
                sw.Start();
                foreach (var item in list)
                {
                    thList.Add(new TaskFactory().StartNew(()=> {
                        var res = createItem(item);
                        while (res == null)
                        {
                            Console.WriteLine("...........service err,retrying......");
                            Thread.Sleep(5000);
                            res = createItem(item);
                        }
                        if (res.messageId == 10000)
                        {
                            Console.WriteLine($"{item.sku} success");
                        }
                        else
                        {
                            Console.WriteLine($"{item.sku}=>{Newtonsoft.Json.JsonConvert.SerializeObject(res)}");
                        }
                    }));                    
                }
                Task.WaitAll(thList.ToArray());
                sw.Stop();
                Console.WriteLine($".................page {page} complete.........{sw.Elapsed.Milliseconds}");
                page++;
            } while (list.Count > 0);
           
            Console.WriteLine("-----------------------all done----------------------------------");
            Console.ReadKey();
        }
        public ResponseBase createItem(JDItem item)
        {
            ResponseBase result = new ResponseBase { messageId=-1 };
            try
            {
                item.content_desc = string.IsNullOrEmpty(item.content_desc) ? "暂无描述" : item.content_desc;
                ItemEntity entity = new ItemEntity();
                entity.goods_sn = item.sku;
                entity.category_id = item.c3_id; //dao.QuerySingleCategory(item.c3_name);
                entity.last_cost = item.last_cost.GetValueOrDefault();
                entity.item_upcs = new Upc[] { new Upc { upc = item.upc, is_delete = 0, is_unique = 1 } };
                entity.upc_code = item.upc;
                if (!string.IsNullOrEmpty(item.publishers) && item.publishers.Length > 2)
                {
                    entity.brand_id = brandList.FirstOrDefault(p => p.brand_name == item.publishers).brand_id;
                }
                else
                {
                    entity.brand_id = 0;
                }
                entity.vendor_id = 1;
                entity.manufacturer_part_number = item.isbn;
                entity.itemShortDescList = new ItemShortDesc[] { new ItemShortDesc { title = item.name }, new ItemShortDesc { title = item.name, language_id = "en_US" } };
                entity.itemDescList = new ItemDesc[] { new ItemDesc { overview = BuildDescription(item) } };
                entity.pmList = new PM[] { new PM { pm_id = 338, pm_name = "Acro Chao" } };
                entity.itemPriceList = new ImItemPriceSetting[] { new ImItemPriceSetting { unit_price = item.unit_price.HasValue ? item.unit_price.Value : 1m } };
                entity.itemPropertyList = GetProperty(item);
                var str = Newtonsoft.Json.JsonConvert.SerializeObject(entity);
                result = ServiceHelper.CallService<ResponseBase>("http://centralapi.ecnow.tech/im/item/insert", entity, Common.token);
            }
            catch (Exception ex)
            {
               
            }           
            return result;
        }

        public void  processToMongo() {
            var data = dao.QueryJdItem(1,10000);
            MongoContext mc = new MongoContext();
            var db = mc.DbSet<JDItem>("items");
            db.AddList(data);
            System.Console.WriteLine("jd to mongo导入完成");
            System.Console.ReadKey();
        }
        /// <summary>
        /// 批量上架
        /// </summary>
        public void ProcessOnLine()
        {
       
            var list = new List<ItemEntity>();
            int page = 1;
            int pageSize = 10;
            do
            {
                list = dao.QueryAllItem(page, pageSize);
                while (OnLineItem(list) == null)
                {
                    Console.WriteLine("...........service err,retrying......");
                    Thread.Sleep(10000);
                }
                Console.WriteLine($"{page * pageSize} success");
                Console.WriteLine($".................page {page} complete.........");
                page++;
            } while (list.Count > 0);

            Console.WriteLine("-----------------------all done----------------------------------");
            Console.ReadKey();           
        }
        public object OnLineItem(List<ItemEntity> list)
        {
            var itemList = list.Select(p=>p.item_number).ToList();
            var entity = new
            {
                status = "A",
                itemList,
                platChannelList = new PlatChannel[1] { new PlatChannel() }
            };
            var str = Newtonsoft.Json.JsonConvert.SerializeObject(entity);
            var result = ServiceHelper.CallService<ResponseBase>("http://centralapi.ecnow.tech/im/item/batchUpdateStatusV2", entity, Common.token);
            if (result != null && result.messageId != 10000 ||!result.success)
            {
                Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(result));
            }
            Thread.Sleep(100);
            return result;
        }


        private string GetItemDescription(string title, string content)
        {
            if (string.IsNullOrWhiteSpace(content))
            {
                return "";
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("<div  style=\"font: Arial,Verdana;width: 100%; text-align: left;\">");
            sb.Append("<div style=\"overflow: hidden; margin: 0 20px;padding: 20px 0 20px;\">");
            sb.Append("<div>");
            sb.Append(
                    "<span style=\"background: #f25950; width: 105px; height: 25px; line-height: 28px; display: block; color: #fff; position: absolute; font-size: 14px; padding-left: 20px; border-top-left-radius: 0.5em;\">"
                            + title + "</span>");
            sb.Append(
                    "<h3 style=\"padding-top:0;font-size: 14px; line-height: 38px; width: 150px; height: 0px; overflow: hidden; color: #FFF; border-left: 50px solid transparent; border-right: 50px solid transparent; border-bottom: 25px solid #f25950; margin: 0px 10px 0 -50px; margin-left: 5px; position: inherit;\"></h3>");
            sb.Append("<div style=\"border-bottom: 3px solid #f25950;\"></div>");
            sb.Append("</div>");
            sb.Append("<div style=\"padding: 18px 10px 0;\">");
            sb.Append("<div style=\"line-height: 24px;\">");
            sb.Append(content);
            sb.Append("</div>");
            sb.Append("</div>");
            sb.Append("</div>");
            sb.Append("</div>");
            return sb.ToString();
        }


        public string BuildDescription(JDItem book)
        {
            StringBuilder sb = new StringBuilder();
            //sb.Append(GetPropertyInfo(book));
            sb.Append(GetItemDescription("编辑推荐", book.editer_desc));
            sb.Append(GetItemDescription("内容简介", book.content_desc));
            sb.Append(GetItemDescription("作者简介", book.author_desc));
            sb.Append(GetItemDescription("精彩书评", book.comments));
            sb.Append(GetItemDescription("目录", book.catalogue));
            sb.Append(GetItemDescription("精彩书摘", book.book_abstract));
            if (!string.IsNullOrWhiteSpace(book.introduction))
            {
                string pattern = "<img.*src=(.*?)[^>]*?>";
                // 现在创建 matcher 对象
                string introduction = Regex.Replace(book.introduction, pattern, "");
                sb.Append(GetItemDescription("前言/序言", introduction));
            }
            return sb.ToString();
        }
        private PropertyInfo[] GetProperty(JDItem book)
        {
            var info=GetPropertyInfo(book);
            List<PropertyInfo> propertyList = new List<PropertyInfo>();
            var propterty = dao.QueryProperty(book.c3_id);
            //foreach (var item in info)
            //{                
              
            //        propertyList.Add(new PropertyInfo
            //        {                    
            //            user_input = item.Value,
            //            user_input_eng = item.Value
            //        });
            
            //}
            return propertyList.ToArray();
        }
        private Dictionary<string,string> GetPropertyInfo(JDItem book)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
        
            result.Add("品牌属地", "中国");            
            if (!string.IsNullOrEmpty(book.publishers))
            {
                result.Add("品牌", book.publishers);
                result.Add("出版社", book.publishers);               
            }
            if (!string.IsNullOrEmpty(book.isbn))
            {
                result.Add("ISBN", book.isbn);              
            }
            if (!string.IsNullOrEmpty(book.book_package))
            {
                result.Add("包装", book.book_package);              
            }
            if (!string.IsNullOrEmpty(book.publish_time))
            {
                result.Add("出版时间", book.publish_time);
            }
            if (!string.IsNullOrEmpty(book.pages))
            {
                result.Add("页码", book.pages);              
            }
            if (!string.IsNullOrEmpty(book.papers))
            {
                result.Add("用纸", book.papers);              
            }
            if (!string.IsNullOrEmpty(book.author))
            {
                string author = book.author;
                if (!string.IsNullOrEmpty(book.editer))
                {
                    author += "," + book.editer;
                }
                if (!string.IsNullOrEmpty(book.transfer))
                {
                    author += "," + book.transfer;
                }
                if (!string.IsNullOrEmpty(book.drawer))
                {
                    author += "," + book.drawer;
                }
                result.Add("编者", author);              
            }           
            if (!string.IsNullOrEmpty(book.language))
            {
                result.Add("语言", book.language);                
            }
            if (book.print_no>0)
            {
                result.Add("版次", book.print_no.ToString());                
            }
            if (!string.IsNullOrEmpty(book.print_time))
            {
                result.Add("印刷时间", book.print_time);               
            }
            return result;
        }
    }
}
